package com.bhs.sansong.ui.orderDispose;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.PictureShowAdapter3;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.base.BaseFragment;
import com.bhs.sansong.bean.AbnormalOrderDetailBean;
import com.bhs.sansong.bean.OrderScheduleBean;
import com.bhs.sansong.bean.OrderScheduleEvent;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.wallet.BalanceActivity;
import com.bhs.sansong.utils.DateUtils;
import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.MyUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.util.SmartGlideImageLoader;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

//异常单处理进度
public class AbnormalOrderScheduleFragment extends BaseFragment implements View.OnClickListener, NetCallBack {

    private ImageView mIvStatus;
    private TextView mTvStatus;

    private RecyclerView mRvList;
    private BaseQuickAdapter<OrderScheduleBean, BaseViewHolder> mAdapter;
    private LinearLayout mLlTopStatus;

    private int id;
    private LinearLayout mLlDispose;
    private TextView mTvTime;
    private TextView mTvConductor;
    private TextView mTvMoney;
    private TextView mTvContent;
    private RecyclerView mRvPicture;
    private PictureShowAdapter3 showAdapter3;
    private TextView mTvReject;
    private TextView mTvRevocation;
    private TextView mTvConsent;
    private TextView mTvCheck;

    public static AbnormalOrderScheduleFragment newInstance(Bundle bundle) {
        AbnormalOrderScheduleFragment fragment = new AbnormalOrderScheduleFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_abnormal_order_schedule;
    }

    @Override
    public void initView(View root) {
        id = getArguments().getInt("id");
        mIvStatus = root.findViewById(R.id.iv_status);
        mTvStatus = root.findViewById(R.id.tv_status);
        mRvList = root.findViewById(R.id.rv_list);
        mLlTopStatus = root.findViewById(R.id.ll_top_status);
        root.findViewById(R.id.ll_service).setOnClickListener(this);
        mLlDispose = root.findViewById(R.id.ll_dispose);
        mTvTime = root.findViewById(R.id.tv_time);
        mTvConductor = root.findViewById(R.id.tv_conductor);
        mTvMoney = root.findViewById(R.id.tv_money);
        mTvContent = root.findViewById(R.id.tv_content);
        mRvPicture = root.findViewById(R.id.rv_picture);
        mTvReject = root.findViewById(R.id.tv_reject);
        mTvRevocation = root.findViewById(R.id.tv_revocation);
        mTvConsent = root.findViewById(R.id.tv_consent);
        mTvReject.setOnClickListener(this);
        mTvRevocation.setOnClickListener(this);
        mTvConsent.setOnClickListener(this);
        mTvCheck = root.findViewById(R.id.tv_check);
        mTvCheck.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mAdapter = new BaseQuickAdapter<OrderScheduleBean, BaseViewHolder>(R.layout.item_order_schedule) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, OrderScheduleBean item) {
                helper.setText(R.id.tv_time, DateUtils.getTime(item.getHandle_time()));
                helper.setText(R.id.tv_conductor, item.getHandle_people());
                helper.setText(R.id.tv_money, String.format("%s元", item.getHandle_money()));
                helper.setText(R.id.tv_content, item.getHandle_content());
                helper.setVisible(R.id.bottom_line, helper.getLayoutPosition() != mData.size() - 1);
                MyUtils.getAbnormalStatus(helper.getView(R.id.tv_status), item.getStatus());
                helper.setGone(R.id.rv_list,!TextUtils.isEmpty(item.getHandle_imgs()));
                if (!TextUtils.isEmpty(item.getHandle_imgs())) {
                    LogUtils.d(item.getHandle_imgs());
                    Object[] images = item.getHandle_imgs().split(",");
                    PictureShowAdapter3 showAdapter3 = new PictureShowAdapter3(Arrays.asList(images));
                    RecyclerView rvList = helper.getView(R.id.rv_list);
                    rvList.setAdapter(showAdapter3);
                    rvList.setLayoutManager(new GridLayoutManager(getContext(), 3));
                    showAdapter3.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                            new XPopup.Builder(getContext())
                                    .asImageViewer(view.findViewById(R.id.iv_picture), position, Arrays.asList(images), null, new SmartGlideImageLoader())
                                    .isShowSaveButton(false)
                                    .show();
                        }
                    });
                }
                helper.setGone(R.id.rv_list, !TextUtils.isEmpty(item.getHandle_imgs()));
            }
        };
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter.setEmptyView(LayoutInflater.from(getContext()).inflate(R.layout.layout_empty, null));
    }


    @Override
    public void onResume() {
        super.onResume();
        loadingPopupShow();
        networkRequest(netApi.get_abnormal_info(id), this);
    }


    private void setData(AbnormalOrderDetailBean abnormalOrderDetailBean) {
        OrderScheduleEvent event = new OrderScheduleEvent(abnormalOrderDetailBean.getData().getHandle_log(),
                abnormalOrderDetailBean.getData().getStatus(), abnormalOrderDetailBean.getData().getId(), abnormalOrderDetailBean.getData().getHandle_money());

        mLlDispose.setVisibility(View.GONE);
        mTvCheck.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(event.getHandle())) {
            Type type = new TypeToken<List<OrderScheduleBean>>() {
            }.getType();
            List<OrderScheduleBean> list = new Gson().fromJson(event.getHandle(), type);
            list.get(0).setStatus(event.status);
            mAdapter.setNewData(list);
        }
        if (event.status.equals("1")) {
            mLlTopStatus.setVisibility(View.VISIBLE);
            mIvStatus.setImageResource(R.mipmap.ic_await);
            mTvStatus.setText("等待专线反馈...");
        } else if (event.status.equals("2")) {
            mLlDispose.setVisibility(View.VISIBLE);
            mTvTime.setText(DateUtils.getTime(abnormalOrderDetailBean.getData().getHandle_time()));
            mTvConductor.setText(abnormalOrderDetailBean.getData().getHandle_people());
            mTvMoney.setText(abnormalOrderDetailBean.getData().getHandle_money());
            mTvContent.setText(abnormalOrderDetailBean.getData().getHandle_content());
            mTvReject.setText(String.format("拒绝(%s/3)", abnormalOrderDetailBean.getData().getReject_num()));
            if (!TextUtils.isEmpty(abnormalOrderDetailBean.getData().getHandle_imgs())) {
                Object[] images = abnormalOrderDetailBean.getData().getHandle_imgs().split("\\|\\|");
                showAdapter3 = new PictureShowAdapter3(Arrays.asList(images));
                mRvPicture.setAdapter(showAdapter3);
                mRvPicture.setLayoutManager(new GridLayoutManager(getContext(), 3));
            } else {
                mRvPicture.setVisibility(View.GONE);
            }
            mLlTopStatus.setVisibility(View.GONE);
        } else if (event.status.equals("3")) {
            mLlTopStatus.setVisibility(View.VISIBLE);
            mIvStatus.setImageResource(R.mipmap.ic_await);
            mTvStatus.setText("等待专线反馈...");
        } else if (event.status.equals("5")) {
            mLlTopStatus.setVisibility(View.VISIBLE);
            mIvStatus.setImageResource(R.mipmap.ic_under_review);
            mTvStatus.setText("受理已完成，等待专线支付中...");
        } else if (event.status.equals("7")) {
            mLlTopStatus.setVisibility(View.VISIBLE);
            mIvStatus.setImageResource(R.mipmap.ic_accomplish);
            mTvStatus.setText("赔偿金额已打入到您的余额里");
            Spanned PageView = Html.fromHtml("您可在:<font color=\"#495EF4\">“我的-余额”</font>中查看");
            mTvCheck.setText(PageView);
            mTvCheck.setVisibility(View.VISIBLE);
        } else {
            mLlTopStatus.setVisibility(View.VISIBLE);
            mIvStatus.setImageResource(R.mipmap.ic_revocation2);
            mTvStatus.setText("客户投诉已撤销");
        }


    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_reject:
                handle(3);
                break;
            case R.id.tv_consent:
                handle(5);
                break;
            case R.id.tv_revocation:
                handle(0);
                break;
            case R.id.tv_check:
                startActivity(new Intent(getContext(), BalanceActivity.class));
                break;
        }
    }

    private void handle(int i) {
        String hint = null;
        if (i == 3) {
            hint = "确定驳回吗？";
        } else if (i == 5) {
            hint = "确定同意吗？";
        } else {
            hint = "确定撤销吗？";
        }
        new XPopup.Builder(getContext())
                .asConfirm("提示", hint,
                        "取消", "确定",
                        new OnConfirmListener() {
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            public void onConfirm() {
                                if (i > 0) {
                                    networkRequest(netApi.handle_abnormal_handle(id, i), AbnormalOrderScheduleFragment.this, 555);
                                } else {
                                    networkRequest(netApi.cancel_abnormal(id), AbnormalOrderScheduleFragment.this, 555);
                                }
                            }
                        }, null, false)
                .show();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            loadingPopupDismiss();
            AbnormalOrderDetailBean detailBean = new Gson().fromJson(json, AbnormalOrderDetailBean.class);
            if (detailBean.isStatus()) {
                setData(detailBean);
            }
        } else {
            BaseBean detailBean = new Gson().fromJson(json, BaseBean.class);
            if (detailBean.isStatus()) {
                networkRequest(netApi.get_abnormal_info(id), this);
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }
}
